﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using System.Text.RegularExpressions;

namespace _4DJackPot
{
    public partial class BUY : Dock
    {

        string[] companies_id;
        string[] companies_name;
        long tot;

        public BUY()
        {
            InitializeComponent();
            tot = 0;
            totAlabel.Text = "Total Amount : " + tot + " KRW";
            this.rB_Yes.Select();
            rB_big.Select();
            string selectQuery = 
                "select company_id, company_name from companies";
            DbConn conn = new DbConn();
            
            DataSet resultReadDataSet = conn.ReadQuery(selectQuery);

            if (resultReadDataSet == null)
            {
                MessageBox.Show("Can`t connect to DB. Please check the DB.","Help", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            else if (resultReadDataSet.Tables[0].Rows.Count == 0)
            {
                MessageBox.Show("there are no available companies","Help", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            else
            {
                int len = resultReadDataSet.Tables[0].Rows.Count;
                companies_id = new string[len];
                companies_name = new string[len];
                int i = 0;
                foreach (DataRow row in resultReadDataSet.Tables[0].Rows)
                {
                    companies_id[i] = row["company_id"].ToString();
                    companies_name[i++] = row["company_name"].ToString();
                }

                this.cB_company.Items.AddRange(companies_name);
            }

            selectQuery =
                "select distinct draw_datetime from games";

            conn = new DbConn();
            resultReadDataSet = conn.ReadQuery(selectQuery);
            if (resultReadDataSet == null)
            {
                MessageBox.Show("Can`t connect to DB. Please check the DB.", "Help", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            else if (resultReadDataSet.Tables[0].Rows.Count == 0)
            {
                MessageBox.Show("there are no available draw date", "Help", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            else
            {
                int count = 0;
                foreach (DataRow row in resultReadDataSet.Tables[0].Rows)
                {
                    string str = row["draw_datetime"].ToString();
                    DateTime d = DateTime.Parse(str);
                    if (DateTime.Compare(DateTime.Now, d) <= 0)
                    {
                        break;
                    }
                    count++;
                }

                int len = resultReadDataSet.Tables[0].Rows.Count - count;
                string[] date = new string[len];
                int i = 0;
                
                foreach (DataRow row in resultReadDataSet.Tables[0].Rows)
                {
                    string str = row["draw_datetime"].ToString();
                    DateTime d = DateTime.Parse(str);
                    if (DateTime.Compare(DateTime.Now, d) <= 0)
                    {
                        if(str != null)
                            date[i++] = str;
                    }                    
                }

                if (date == null)
                {

                }
                else
                {
                    this.cB_date.Items.AddRange(date);
                    this.cB_date.SelectedIndex = 0;
                }
            }
        }

        private int count = 0;
        
        //private void btn_join_Click(object sender, EventArgs e)
        //{
        //    try
        //    {
        //        Join join = new Join();
        //        join.ShowDialog();
        //    }
        //    catch (Exception e1)
        //    {
        //        FileLog FileLog = new FileLog();
        //        FileLog.WriteErrorLog(e1.StackTrace + "\n" + e1.Message);
        //    }
        //}

        private void button2_Click(object sender, EventArgs e)
        {
            if (!checkEmpty())
            {
                MessageBox.Show("Please fill in the all blank", "도움말", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            string totnum = "";
            string[] num = new string[4];
            num[0] = this.tB_num1.Text;
            num[1] = this.tB_num2.Text;
            num[2] = this.tB_num3.Text;
            num[3] = this.tB_num4.Text;

            string[] selectedNum = new String[24];
            
            if (this.rB_Yes.Checked)
            {
                makePermutation(num,selectedNum);
            }
            else
            {
                selectedNum[0] = num[0] + num[1] + num[2] + num[3];
                count = 1;
            }

            for (int i = 0;i < count; i++)
            {
                int rowIndex = 0;
                
                rowIndex = this.dGV_buyInfo.RowCount;
                this.dGV_buyInfo.Rows.Insert(rowIndex);
                this.dGV_buyInfo["dGv_Bets_DrawDate", rowIndex].Value = this.cB_date.Text;
                this.dGV_buyInfo["dGv_Bets_Company", rowIndex].Value = this.cB_company.Text;
                this.dGV_buyInfo["dGv_Bets_Number", rowIndex].Value = selectedNum[i];

                if (rB_Yes.Checked)
                {
                    this.dGV_buyInfo["dGv_Bets_Permute", rowIndex].Value = "Yes";
                }
                else
                {
                    this.dGV_buyInfo["dGv_Bets_Permute", rowIndex].Value = "No";
                }
              
                if (rB_big.Checked)
                {
                    this.dGV_buyInfo["dGv_Bets_cast", rowIndex].Value = "Big";
                    totnum = this.tB_betAmount.Text + ",000";
                    this.dGV_buyInfo["dGv_Bets_Amount", rowIndex].Value = totnum;
                    totnum = totnum.Replace(",", "");
                    totnum = totnum.Substring(0, totnum.Length - 3);
                    tot += Convert.ToInt32(totnum);
                }
                else if (rB_small.Checked)
                {
                    this.dGV_buyInfo["dGv_Bets_cast", rowIndex].Value = "Small";
                    totnum = this.tB_betAmount.Text + ",000";
                    this.dGV_buyInfo["dGv_Bets_Amount", rowIndex].Value = totnum;
                    totnum = totnum.Replace(",", "");
                    totnum = totnum.Substring(0, totnum.Length - 3);
                    tot += Convert.ToInt32(totnum);
                }
                else
                {
                    this.dGV_buyInfo["dGv_Bets_cast", rowIndex].Value = "Big";
                    totnum = this.tB_betAmount.Text + ",000";
                    this.dGV_buyInfo["dGv_Bets_Amount", rowIndex].Value = totnum;
                    totnum = totnum.Replace(",", "");
                    totnum = totnum.Substring(0, totnum.Length - 3);
                    tot += Convert.ToInt32(totnum);

                    this.dGV_buyInfo.Rows.Insert(rowIndex + 1);
                    this.dGV_buyInfo["dGv_Bets_DrawDate", rowIndex + 1].Value = this.cB_date.Text;
                    this.dGV_buyInfo["dGv_Bets_Company", rowIndex + 1].Value = this.cB_company.Text;
                    this.dGV_buyInfo["dGv_Bets_Permute", rowIndex + 1].Value = this.dGV_buyInfo["dGv_Bets_Permute", rowIndex].Value;
                    totnum = this.tB_betAmount.Text + ",000";
                    this.dGV_buyInfo["dGv_Bets_Amount", rowIndex + 1].Value = totnum;
                    totnum = totnum.Replace(",", "");
                    totnum = totnum.Substring(0, totnum.Length - 3);
                    tot += Convert.ToInt32(totnum);
                    this.dGV_buyInfo["dGv_Bets_Number", rowIndex + 1].Value = selectedNum[i];
                    this.dGV_buyInfo["dGv_Bets_cast", rowIndex + 1].Value = "Small";
                }

                if (tot >= 100000000 || this.dGV_buyInfo.Rows.Count >= 200)
                {
                    MessageBox.Show("You have added too much to buy at once. "+(count-i)+" data can`t be added.", "도움말", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    
                    warning.Text = "** For smooth functioning of the program, you can puchase up to 200 number or about 100 billion KRW at once.";
                    break;
                }
            }
            count = 0;
            tot = tot * 1000;

            totAlabel.Text = "Total Amount : " + tot.ToString("###,##0") + " KRW";
            
        }

        private void button5_Click(object sender, EventArgs e)
        {

            this.dGV_buyInfo.EndEdit();
            List<int> selectedRows = new List<int>();

            for (int j = 0; j < this.dGV_buyInfo.SelectedCells.Count; j++)
            {
                if (selectedRows.Contains(this.dGV_buyInfo.SelectedCells[j].RowIndex))
                    continue;
                selectedRows.Add(this.dGV_buyInfo.SelectedCells[j].RowIndex);
            }
            if (selectedRows.Count == 0)
            {
                MessageBox.Show("There are no data to delete","도움말", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            DialogResult result =
MessageBox.Show(String.Format("Do you want to delete {0} data?", selectedRows.Count.ToString()), "도움말", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (result != DialogResult.OK)
                return;

            int subtot = 0;
            selectedRows.Sort();
            selectedRows.Reverse();
            for (int i = 0; i < selectedRows.Count; i++)
            {
                string temp = this.dGV_buyInfo["dGv_Bets_Amount", selectedRows[i]].Value.ToString();
                this.dGV_buyInfo.Rows.RemoveAt(selectedRows[i]);
                temp = temp.Replace(",", "");
                temp = temp.Substring(0, temp.Length - 3);
                subtot += Convert.ToInt32(temp);
            }
            tot = tot - subtot;
            totAlabel.Text = "Total Amount : " + tot + "000 KRW";
            if (tot < 100000000 || dGV_buyInfo.Rows.Count < 200)
            {
                warning.Text = "";
            }
            MessageBox.Show("Deletion is completed", "도움말", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }


        //베팅 숫자 값에 숫자가 아닌 다른 값이 들어가는 경우 그 값을 무효화시킨다.
        //숫자가 칸에 들어가면 자동으로 다음 칸으로 옮겨준다.
        private void tB_num1_TextChanged(object sender, EventArgs e)
        {
            Regex regex = new Regex(@"[^\d]+");
            if (!regex.IsMatch(tB_num1.Text))
            {
                tB_num2.Focus();
            }
            else
            {
                tB_num1.Text = "";
            }
        }

        private void tB_num2_TextChanged(object sender, EventArgs e)
        {
            Regex regex = new Regex(@"[^\d]+");
            if (!regex.IsMatch(tB_num2.Text))
            {
                tB_num3.Focus();
            }
            else
            {
                tB_num2.Text = "";
            }
        }

        private void tB_num3_TextChanged(object sender, EventArgs e)
        {
            Regex regex = new Regex(@"[^\d]+");
            if (!regex.IsMatch(tB_num3.Text))
            {
                tB_num4.Focus();
            }
            else
            {
                tB_num3.Text = "";
            }
        }

        private void tB_num4_TextChanged(object sender, EventArgs e)
        {
            Regex regex = new Regex(@"[^\d]+");
            if (!regex.IsMatch(tB_num4.Text))
            {

            }
            else
            {
                tB_num4.Text = "";
            }
        }

        //베팅할 돈을 입력할 때 숫자가 아닌 다른 값이 들어오면 무시한다.
        private void tB_betAmount_TextChanged(object sender, EventArgs e)
        {
            if (tB_betAmount.Text == "")
                return;

            Regex regex = new Regex(@"[^\d]+");
            if (!regex.IsMatch(tB_betAmount.Text.Substring(tB_betAmount.Text.Length-1)))
            {
                if (tB_betAmount.Text == "0")//0만 들어온 경우 0원이므로 무시
                {
                    tB_betAmount.Text = "";
                    tB_betAmount.Focus();
                    tB_betAmount.Select(tB_betAmount.Text.Length, 0);
                }
                
                string[] temp = tB_betAmount.Text.Split(',');
                if (tB_betAmount.Text.Length > 3 && temp[temp.Length-1].Length > 3)
                {
                    string str = tB_betAmount.Text;
                    str = str.Replace(",", "");
                    int len = str.Length;

                    for (int i = 0; i < (len-1) / 3; i++)
                    {
                        str = str.Substring(0, len - 3 * (i + 1)) + "," + str.Substring(len - 3 * (i + 1));
                    }
                    tB_betAmount.Text = str;
                    tB_betAmount.Select(tB_betAmount.Text.Length, 0);
                }
            }
            else
            {
                String str = tB_betAmount.Text;
                str = str.Substring(0, str.Length - 1);
                tB_betAmount.Text = str;
                tB_betAmount.Focus();
                tB_betAmount.Select(tB_betAmount.Text.Length, 0);
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("Do you want to buy the numbers in the list?","Important Question", MessageBoxButtons.YesNo);
            if (result == DialogResult.No)
                return;
            
            //테이블 값들을 db에 넣기
            this.dGV_buyInfo.EndEdit();
            
            if (this.dGV_buyInfo.Rows.Count == 0)
            {
                MessageBox.Show("There is nothing to buy.","도움말", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

 //           Boolean success = false;

            for (int i = 0; i < this.dGV_buyInfo.Rows.Count; i++)
            {
                string game_id = "";//draw날짜+회사번호
                string forecast;//big or small
                string bet_num;//4자리 숫자
                string bet_amount;
                string bet_datetime;//구매 날짜
                
                for (int j = 0; j < companies_name.Length; j++)
                {
                    if (companies_name[j].Equals(this.dGV_buyInfo["dGv_Bets_Company", i].Value.ToString()))
                    {
                        string selectQuery =
                            "SELECT DISTINCT games.game_id FROM company_games, games " +
                            "WHERE company_id = "+companies_id[j]+" AND draw_datetime = '"+this.dGV_buyInfo["dGv_Bets_DrawDate", i].Value.ToString()+"'";
                        DbConn conn = new DbConn();
                        DataSet resultReadDataSet = conn.ReadQuery(selectQuery);

                        if (resultReadDataSet == null)
                        {
                            MessageBox.Show("Can`t connect to DB. Please check the DB.", "Help", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }
                        else if (resultReadDataSet.Tables[0].Rows.Count == 0)
                        {
                            MessageBox.Show("unavailable games", "Help", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }
                        else
                        {
                            game_id = resultReadDataSet.Tables[0].Rows[0]["game_id"].ToString() ?? "";
                        }
                        break;
                    }
                }
                
                forecast = this.dGV_buyInfo["dGv_Bets_cast", i].Value.ToString();
                bet_num = this.dGV_buyInfo["dGv_Bets_Number", i].Value.ToString();
                bet_amount = this.dGV_buyInfo["dGv_Bets_Amount", i].Value.ToString().Replace(",","");
                bet_datetime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                string insertQueryString;

                if (this.dGV_buyInfo["dGv_Bets_Permute", i].Value.ToString().Equals("Yes"))
                {
                    insertQueryString =
                    "INSERT INTO bets(game_id,user_id,bet_number,bet_amount,bet_datetime,forecast,permitation) " +
                "VALUES('" + game_id + "','" + Global.idString + "','" + bet_num + "','" + bet_amount + "','" + bet_datetime + "','" + forecast + "',1)";
                }
                else
                {
                    insertQueryString =
                    "INSERT INTO bets(game_id,user_id,bet_number,bet_amount,bet_datetime,forecast,permitation) " +
                "VALUES('" + game_id + "','" + Global.idString + "','" + bet_num + "','" + bet_amount + "','" + bet_datetime + "','" + forecast + "',0)";
                }
                
                DbConn Conn = new DbConn();
                if (!Conn.InsertQuery(insertQueryString))
                    return;    
            }

            MessageBox.Show("You have successfully bought.", "도움말", MessageBoxButtons.OK, MessageBoxIcon.Information);
            this.Close();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            System.Random r = new System.Random();
            int k = r.Next(0, 9);
            tB_num1.Text = k.ToString();
            k = r.Next(0, 9);
            tB_num2.Text = k.ToString();
            k = r.Next(0, 9);
            tB_num3.Text = k.ToString();
            k = r.Next(0, 9);
            tB_num4.Text = k.ToString();
        }

        private Boolean checkEmpty()
        {
            if (cB_company.SelectedItem == null)
            {
                return false;
            }
            if (tB_betAmount.Text == "")
            {
                return false;
            }
            if (tB_num1.Text == "" || tB_num2.Text == "" || tB_num3.Text == "" || tB_num4.Text == "")
            {
                return false;
            }
            return true;
        }

        private void makePermutation(String[] num, String[] selectNum)
        {
            permut(num, 0, selectNum);
        }

        void swap(string[] num, int i, int j)
        {
            string temp = num[i];
            num[i] = num[j];
            num[j] = temp;
        }

        void permut(string[] num, int cur, string[] selectNum)
        {
            if (cur == 3)
            {
                Boolean already = false;
                string temp = num[0] + num[1] + num[2] + num[3];
                for (int i = 0; i < count; i++)
                {
                    if (selectNum[i].Equals(temp))
                        already = true;
                }
                if(!already)
                    selectNum[count++] = temp;
            }
            else
            {
                for (int i = cur; i < 4; i++)
                {
                    swap(num, cur, i);
                    permut(num, cur + 1, selectNum);
                    swap(num, cur, i);
                }
            }
        }

        private void dT_date_ValueChanged(object sender, EventArgs e)
        {

        }

        private void button6_Click(object sender, EventArgs e)
        {
            tB_betAmount.Text = "5";
        }

        private void button7_Click(object sender, EventArgs e)
        {
            tB_betAmount.Text = "10";
        }

        private void button8_Click(object sender, EventArgs e)
        {
            tB_betAmount.Text = "50";
        }

        private void button9_Click(object sender, EventArgs e)
        {
            tB_betAmount.Text = "100";
        }

        private void BUY_Load(object sender, EventArgs e)
        {
            this.cB_company.SelectedIndex = 0;
        }
    }
}
